package com.ruoyi.assemble.datamanage.controller;

import com.ruoyi.assemble.datamanage.domain.FileMenu;
import com.ruoyi.assemble.datamanage.domain.LoadRecord;
import com.ruoyi.assemble.datamanage.domain.SaveRow;
import com.ruoyi.assemble.datamanage.domain.TableConfig;
import com.ruoyi.assemble.datamanage.domain.dto.DataLoadRecordQuery;
import com.ruoyi.assemble.datamanage.service.impl.DataLoadServiceImpl;
import com.ruoyi.assemble.datamanage.domain.dto.FileSetResult;
import com.ruoyi.assemble.suvery.domain.SurveyAnswer;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:  数据加载
 * @author:
 * @date: 2022/7/13 17:30
 * @param:
 * @return:
 **/
@Api(value = "数据加载", tags = "数据加载")
@RestController
@RequestMapping("dataManage/dataLoad")
public class DataLoadController extends BaseController {

    @Resource
    private DataLoadServiceImpl dataLoadService;

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * @description : 获取文件类型
     * @date : 2021/9/15 9:45
     **/
    @GetMapping("/getFileType")
    @ApiOperation(value = "数据加载",notes = "获取本地文件类型树")
    public List<FileMenu> getFileType() {
        return dataLoadService.selectAllType();
    }


    @GetMapping("/getRecordList")
    @ApiOperation(value = "数据加载",notes = "分页列表")
    public TableDataInfo getRecordList(DataLoadRecordQuery argsMap,
                                       @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                       @RequestParam(value = "rows", required = false, defaultValue = "#{T(java.lang.Integer).MAX_VALUE}") int rows) {
        startPage();
        List<LoadRecord> list = dataLoadService.getRecordList(argsMap);
        return getDataTable(list);
    }

    @GetMapping("/getMaintenanceList")
    @ApiOperation(value = "数据维护",notes = "分页列表")
    public TableDataInfo getMaintenanceList(@RequestParam Map argsMap,
                                          @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                          @RequestParam(value = "rows", required = false, defaultValue = "#{T(java.lang.Integer).MAX_VALUE}") int rows) {
        startPage();
        List list = dataLoadService.getMaintenanceList(argsMap);
        return getDataTable(list);
    }


    @GetMapping("/getSetInfo")
    @ApiOperation(value = "数据加载",notes = "列表-设置")
    public FileSetResult getSetInfo(@RequestParam Map argsMap) {
        return dataLoadService.getTableSetInfo(argsMap);
    }


    @PostMapping(value = "/loadTableData")
    @ApiOperation(value = "数据加载",notes = "列表-加载")
    public Map<String, String> loadTableData(
        @RequestParam Map argsMap
    ) {
        return dataLoadService.loadData(argsMap);
    }

    @GetMapping("/deleteData")
    @ApiOperation(value = "数据加载",notes = "列表-删除单条加载数据和文件")
    public ResponseEntity deleteData(@RequestParam Map argsMap) {
        dataLoadService.deleteData(argsMap);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/downloadTemplate")
    @ApiOperation(value = "数据加载",notes = "模板下载")
    public ResponseEntity downloadParamTemplate(@RequestParam(value = "name", required = false) String name,
                                     @RequestParam(value = "path", required = true) String path,
                                     @RequestParam(value = "type", required = false) String type) throws UnsupportedEncodingException {
        String realPath = path;
        org.springframework.core.io.Resource resource = resourceLoader.getResource(realPath);
        return ResponseEntity.ok()
            .header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=\"%s\"", URLEncoder.encode( name,"UTF-8")))
            .body(resource);
    }

    @PostMapping(value = "/uploadingFile")
    @ApiOperation(value = "数据加载",notes = "文件上传")
    public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file,
                                     @RequestParam(value = "projectId", required = false) String projectId,
                                  @RequestParam(value = "typeId", required = false) String typeId,
                                  @RequestParam(value = "stepId", required = false) String stepId,
                                  @RequestParam(value = "nodeId", required = false) String nodeId,
                                  @RequestParam(value = "typeName", required = false) String typeName,
                                  @RequestParam(value = "parentType", required = false) String parentType,
                                  @RequestParam(value = "userCode", required = false) String userCode) {
        return ResponseEntity.ok(dataLoadService.uploadFile(file, projectId, typeId, stepId, nodeId, typeName, parentType, userCode));
    }

    @PostMapping(value = "/updateInfo")
    @ApiOperation(value = "数据加载",notes = "设置")
    public ResponseEntity updateInfo(@RequestBody FileSetResult fileSetResult) {
        dataLoadService.updateRecordInfo(fileSetResult);
        return ResponseEntity.ok(new HashMap<>());
    }




    @GetMapping("/selectTableHead")
    @ApiOperation(value = "数据维护",notes = "分页列表")
    public List<TableConfig> selectTableHead(@RequestParam Map argsMap) {
        String tableCode = String.valueOf(argsMap.get("tableCode"));
        return dataLoadService.selectTableHead(tableCode);
    }


    @GetMapping("/deleteMaintenanceRow")
    @ApiOperation(value = "数据维护",notes = "列表-删除单条加载数据和文件")
    public ResponseEntity deleteMaintenanceRow(@RequestParam Map argsMap) {
        dataLoadService.deleteMaintenanceRow(argsMap);
        return ResponseEntity.ok().build();
    }


    /**
     * @param : [params]
     * @description : 保存项目
     * @date : 2021/9/15 9:54
     **/
    @ApiOperation(value = "数据维护", notes = "保存项目")
    @PostMapping("/saveRow")
    public ResponseEntity saveRow(@RequestBody SaveRow params) {
        return dataLoadService.saveRow(params);
    }

    /**
     * @description: 导出
     * @author Ligw
     * @date 2022/7/18 10:14
     */
    @ApiOperation(value = "数据维护",notes = "导出")
    @PostMapping("/downloadPhone")
    public void exportExcel(@RequestParam String tableCode, @RequestParam String projectId, @RequestParam String tableName,HttpServletResponse response) {
        try {
            //取出session中村的手机号，或者直接数据库中查询
            List<String> list = dataLoadService.getExportData(tableCode, projectId);
            //文件名
            String fileName = tableName + ".csv";
            //文件内容
            String text = "";
            if (list != null && !list.isEmpty()) {
                for (String data : list) {
                    text += data + "\r\n";
                }
            }
            OutputStream os = response.getOutputStream();
            BufferedOutputStream buff = new BufferedOutputStream(os);
            response.setHeader("Content-Type", "text/plain");
            response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", URLEncoder.encode(fileName, "UTF-8")));
            buff.write(text.getBytes("GBK"));
            buff.flush();
            buff.close();
            os.close();
        } catch (Exception e) {
            //log.error("导出短信群发手机号：{}",e.getMessage());
        }
    }


}
